package com.heima.common.exception;

import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;




/**
 * 通用异常捕捉
 * 2022/8/6
 * author：jinze
 *
 *
 * */

@RestControllerAdvice
@Slf4j
public class BaseExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ResponseResult handleException(Exception e){
        // 使用日志记录异常
        StackTraceElement[] stackTrace = e.getStackTrace();
        if (stackTrace.length > 0 && stackTrace[0] != null) {
            StackTraceElement traceElement = stackTrace[0];
            String fileName = traceElement.getFileName();
            String methodName = traceElement.getMethodName();
            int lineNumber = traceElement.getLineNumber();
            log.error("------------出现异常--------------");
            log.error("异常位置:{},方法{},第{}行", fileName, methodName, lineNumber);
            log.error("异常信息:{}", e.toString());
        }
        e.printStackTrace();
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }
}
